using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using BoOnce.Components;
using BoOnce.GameLogic.Entities.Drawable.GFX;

namespace BoOnce.Physic
{
    class ParticulesEngine
    {
        #region Attributes
        public ParticulesConfig Config;
        
        public double _DurationBetweenParticule = 150; //ms
        public Vector2 Source = new Vector2(200, 200);
        public Vector2 InitialForce = new Vector2(2500f, 0f);
        public Vector2 InitialForceNoise = new Vector2(1500f, 1000f);

        private List<Particule> _Particules;
        private List<Particule> _ParticulesToRemove;
        private Game _Game;
        private Random _Random;
        private double _NextParticule = 0;
        #endregion

        #region Constructor
        public ParticulesEngine(Game game, ParticulesConfig conf)
        {
            Config = conf;
            _Game = game;
            _Random = new Random();
            _Particules = new List<Particule>();
            _ParticulesToRemove = new List<Particule>();
        }
        #endregion

        public void Update(GameTime gameTime)
        {
            double currentTime = gameTime.TotalGameTime.TotalMilliseconds;
            if (_NextParticule == 0) _NextParticule += _DurationBetweenParticule;

            if (_NextParticule < currentTime)
            {
                Particule newPart = new Particule(_Game.Content.Load<Texture2D>(Settings.CONTENT_GFX_PATH + "/Particules/particule"+_Random.Next(1, 3).ToString()), Source, 1f, currentTime, Config);
                newPart.SetImpulse(InitialForce + (float)(_Random.NextDouble()) * InitialForceNoise);
                _Particules.Add(newPart);
                _NextParticule = currentTime + _DurationBetweenParticule;
            }

            foreach (Particule particule in _Particules)
            {
                if (particule.CreationTime + particule.Config.LifeDuration < currentTime)
                {
                    _ParticulesToRemove.Add(particule);
                }
                particule.Update(gameTime);
                particule.DrawedOrder = 100;
                particule.DEC.Add(particule);
            }

            foreach (Particule particule in _ParticulesToRemove)
            {
                _Particules.Remove(particule);
                particule.Dispose();
            }
            _ParticulesToRemove.Clear();
        }
    }

}
